/**
* <p>Title: TableControlUtil.java</p>
* <p>Description: G7S——TABLE处理utils</p>
* <p>Company: www.huoyunren.com</p>
* @author duanxiangyun
* @date 2015年1月7日
* @version 1.0
*/
package com.hxbd.test.utils.webdriver;

import java.io.File;
import java.util.List;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
 * web中对于table中元素识别、操作等的封装类
 */
public class TableControlUtil {
		private static WebElement webTable;
		private static TableControlUtil t;
	/**
	 * 构造方法:private
	 * @param webElement
	 */
		private TableControlUtil(WebElement webElement) {
		webTable = webElement;
	}
	/**
	 * 初始化单例
	 * @param webElement
	 * @return TableControlUtil
	 */
	public static TableControlUtil getInstance (WebElement webElement) {
		if (t == null) {//延迟创建线程，保证只有第一次使用的时候才实例化。
			synchronized (TableControlUtil.class) {//实现多线程安全又不影响性能（细锁）
				if (t == null) {
					t = new TableControlUtil(webElement);
				}
			}
		}
		return t;
	}

	/**
	 * 得到表格的行数
	 * @return int
	 */
	public int getRowCount() {
		List<WebElement> rowCounts =
		webTable.findElements(By.tagName("tr"));
		return rowCounts.size();
	}
	
	/**
	 * 得到表格thead的列数
	 * @return int
	 */
	public int getColCount() {
		List<WebElement> rowCounts =
		webTable.findElements(By.tagName("th"));
		return rowCounts.size();
	}
	/**
	 * 得到指定行的列数
	 * @param rowIdx
	 * @return int
	 */
	public int getColCount(int rowIdx) {
		try {
			List<WebElement> rowCounts =
			webTable.findElements(By.tagName("tr"));
			// 取得当前的tr
			WebElement rowNum = rowCounts.get(rowIdx);
			// 计算当前的td数
			List<WebElement> colCounts = rowNum.findElements(By.tagName("td"));
			return colCounts.size();
		} catch (NoSuchElementException e) {
			throw new NoSuchElementException("Failed to get the cell");
		}
	}
	
	/**
	 * 根据列数和行数获取元素text
	 * @param driver
	 * @param row
	 * @param colnum
	 * @param trpath
	 * @return String
	 */
	public static String getCellText(WebDriver driver,int row, int colnum, String trpath)
    {
        String text = null;
        //avoid get the head line of the table
        row=row+1;
    
        String xpath = trpath + row + "]/td[" + colnum + "]";
        WebElement table = driver.findElement(By.xpath(xpath)); //*[@id="table138"]/tbody/tr[1]/td[1]/strong
        text=table.getText();
        return text;
        
    }
	/**
	 * 获取excel单元格文本
	 * @param col
	 * @param row
	 * @param filename
	 * @return String
	 */
	public static String getCellContent (int col, int row, String filename) {
		String cell = null;
		try {
	        Workbook book = Workbook.getWorkbook(new File(filename));
	        Sheet sheet = book.getSheet(0);
	        cell = sheet.getCell(col, row).getContents();
		} catch(Exception e){
			e.printStackTrace();
		}
		return cell;
	}
	
}
